// 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。

// 输入：matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
// 输出：[1, 2, 3, 6, 9, 8, 7, 4, 5]

var spiralOrder = function (matrix) {
    const row = matrix.length, columns = matrix[0].length;
    let left = 0, right = columns - 1, top = 0, bottom = row - 1;
    let res = [];
    while (left <= right && top <= bottom) {
        for (let j = left; j <= right; j++) {
            res.push(matrix[top][j]);
        }
        for (let i = top + 1; i <= bottom; i++) {
            res.push(matrix[i][right]);
        }
        if (left < right && top < bottom) {
            for (let j = right - 1; j > left; j--) {
                res.push(matrix[bottom][j]);
            }
            for (let i = bottom; i > top; i--) {
                res.push(matrix[i][left]);
            }
        }
        [left, right, top, bottom] = [left + 1, right - 1, top + 1, bottom - 1];
    }
    return res;
};

const matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
console.log(spiralOrder(matrix));